import { defineComponent, onMounted, PropType, reactive, ReactiveEffect, Ref, ref } from 'vue'
import useExpose from '@/hooks/useExpose'
import Tools from './components/Tools'
import Table from 'ant-design-vue/lib/table'
import { get } from '@/api'

export interface ITableExpose {
  handleGetData: Function;
  table: any;
}

export default defineComponent({
  name: 'MsTable',
  mixins: [Table],
  props: {
    searchForm: {
      type: Object as PropType<object>,
      default: () => ({})
    },
    api: {
      type: String as PropType<string>,
      required: true
    },
    exportName: {
      type: String as PropType<string>,
      default: '表格数据'
    },
    columns: {
      type: Array as PropType<Array<any>>,
      default: () => []
    },
    rowKey: {
      type: String as PropType<string>,
      default: 'id'
    },
    pagination: {
      type: [Object, Boolean] as PropType<boolean | any>,
      default: () => ({
        total: 0,
        pageSize: 10,
        current: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total: number, range: number[]) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      })
    }
  },
  setup(props, { slots }) {
    const table = ref<any>(null)
    const state = reactive({
      tableSpinning: false,
      dataSource: [],
      page: 1,
      limit: 10,
      myPagination: Object.assign(props.pagination),
      cacheColumns: props.columns
    })

    const handleGetData = (page = state.page, limit = state.limit, info = props.searchForm) => {
      state.page = page
      state.limit = limit
      state.tableSpinning = true
      get(props.api, { page, limit, ...info }).then((res) => {
        const { records, total } = res.result
        state.dataSource = records
        state.myPagination.total = total
      }).finally(() => {
        state.tableSpinning = false
      })
    }

    const onTableChange = (pagination: { current: number; pageSize: number }) => {
      state.myPagination = pagination
      handleGetData(pagination.current, pagination.pageSize)
    }

    const toolsFilter = (filter: Array<string>) => {
      state.cacheColumns = props.columns.filter((item) => filter.includes(item.dataIndex || item.slots?.customRender))
    }

    onMounted(handleGetData)

    useExpose({
      handleGetData,
      table
    } as ITableExpose)

    return () => {
      return (
        <>
          <Tools columns={props.columns} exportName={props.exportName} onFilter={toolsFilter} />
          <a-spin spinning={state.tableSpinning}>
            <a-table
              ref={table}
              columns={state.cacheColumns}
              dataSource={state.dataSource}
              row-key={props.rowKey}
              pagination={state.myPagination}
              onChange={onTableChange}
              v-slots={slots}
            />
          </a-spin>
        </>
      )
    }
  }
})
